package com.hecj.common.lib.encryption;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import com.hecj.common.lib.util.Constant;

/**
 * 接口签名工具类
 * @author hecj
 *
 */
public class SignKit {
	
	// 签名字段
	final static String SIGN_FIELD = "sign";

	/**
	 * 签名
	 * @param signObj
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static String sign(Object obj) {
		if(obj instanceof Map) {
			return MD5.md5crypt(getDictStr((Map)obj));
		}
		if(obj instanceof JSONObject) {
			return MD5.md5crypt(getDictStr((JSONObject)obj));
		}
		throw new RuntimeException("暂时不支持此类型生成签名,"+obj.getClass());
	}
	
	/**
	 * JSONObject字段排序拼接
	 * @param obj
	 * @return
	 */
	public static String getDictStr(JSONObject obj) {
		List<String> keys = new ArrayList<String>(obj.keySet());
		keys.remove(SIGN_FIELD);
		Collections.sort(keys);
		StringBuffer str = new StringBuffer(Constant.ApiDesKey);
		for(String key : keys) {
			Object value = obj.get(key);
			if(value == null) {
				value = "";
			}
			str.append(String.valueOf(value));
		}
		return str.toString();
	}
	
	/**
	 * Map字段排序拼接
	 * @param obj
	 * @return
	 */
	public static String getDictStr(Map<String,Object> obj) {
		List<String> keys = new ArrayList<String>(obj.keySet());
		keys.remove(SIGN_FIELD);
		Collections.sort(keys);
		StringBuffer str = new StringBuffer(Constant.ApiDesKey);
		for(String key : keys) {
			Object value = obj.get(key);
			if(value == null) {
				value = "";
			}
			str.append(String.valueOf(value));
		}
		return str.toString();
	}

}
